; Script Start - Add your code below here
; This script requires full Administrative rights
#Include <APIConstants.au3>
#Include <WinAPIEx.au3>

#include <ButtonConstants.au3>
#include <EditConstants.au3>
#include <GUIConstantsEx.au3>
#include <StaticConstants.au3>
#include <WindowsConstants.au3>
;#include <FileLib.au3>
#include <Misc.au3>
#include <File.au3>
#include <Array.au3>
#include <String.au3>
#include <Email.au3>

;_Singleton(@ScriptName, 0)
;define all variables
Dim $var, $AutoRipSettings, $MakeMKVInput, $MakeMKVLocation, $TempInput, $RipLocation, $FinalInput, $OK, $aData2
Dim $Cancel, $SettingsGroup, $ConfirmSettings, $MakeMKVPath, $tempPath, $finalPath, $settingsData, $FinalLocation
Dim $DVDDrive, $DVDSource, $var, $convertAppleTV, $drivetest, $iniFile, $Label1, $Label2, $file, $driveLetter, $MakeMKV
Dim $tempLocation, $finalMovieLocation, $validateSettings, $iniDrive, $ChooseDrive, $runDVDInstaller
Dim $autoripini, $sleepDelay, $MonitorDelay, $moveFiles, $foldercheck, $iMsgBoxAnswer, $finalMKVFile, $finalMKVNewName, $file
Dim $runHandBrakeInstaller, $handbrakePath, $convertUsingHandbrake, $minTitleLength, $handbrakeCommandLine, $keepMKV, $MovieLocation, $doFilesExist
Dim $driveID, $blueRayTitle, $newDriveObject, $versionx, $versiony, $versionz, $makeMKVDownloadName, $handbrakeDownloadName, $episodeSupport,$x
Dim $emailType, $emailTo, $emailCC, $userEmail, $emailSubject, $emailBody, $emailAttachment
Dim $debugLogList, $debugEnable, $drivetocheck

Global $driveLabel
; Define the ini file based on the file version of this script (yes, it includes the .exe but
; this was the simplest way to handle it automatically
$autoripini = @ScriptDir & "\" & StringTrimRight(@ScriptName, 4) & ".ini"
$handbrakeCommandLine = '.mp4" -e x264 -q 20.0 -a 1,1 -E faac,copy:ac3 -B 160,160 -6 dpl2,auto -R Auto,Auto -D 0.0,0.0 -f mp4 -X 720 --loose-anamorphic -m -x cabac=0:ref=2:me=umh:bframes=0:weightp=0:8x8dct=0:trellis=0:subme=6'
; Check to see if the ini file has the correct section.  If not, run the setup
; so that all the correct ini data can be populated.
$iniFile = IniReadSection($autoripini, "AutoRipSettings")

;debugit
; This function is called if the user does not have MakeMKV in the predefined location (yes, its hardcoded).
Func DownloadHandBrake()
	$versionx=0
	$versiony=9
	$versionz=7
	Dim $iMsgBoxAnswer
	; Promp the user with an option to download MakeMKV
	; If the user DOES have it installed in a custom location, they can click cancel and be prompted with the
	; ini settings dialog box.
	$iMsgBoxAnswer = MsgBox(33, "HandbrakeCLI Is Missing - Download?", "HandbrakeCLI as defined in the " & $autoripini & " file cannot be found." & @CRLF & "" & @CRLF & "If you have HandbrakeCLI, Click Cancel to edit your preferences" & @CRLF & "" & @CRLF & "If you would like to download HandbrakeCLI, Click OK")
	; Download the file
	; show a "progress indicator" based on file length.
	; show a "progress indicator" based on file length.
	Select
		Case $iMsgBoxAnswer = 1 ;OK
			If FileExists ("C:\Program Files (x86)") Then
				Do
					If $versionz > 9 Then
						$versionz = 0
						$versiony = $versiony + 1
					EndIf
					If $versiony >9 Then
						$versionz = 0
						$versiony = 0
						$versionx = $versionx + 1
					EndIf
				Local $handbrakeDownloadName = "HandBrake-" & $versionx & "." & $versiony & "."  & $versionz & "-x86_64-Win_GUI.exe"
				Local $hDownload = InetGet("http://downloads.sourceforge.net/project/handbrake/" & $versionx & "." & $versiony & "."  & $versionz & "/" & $handbrakeDownloadName & "?r=&ts=1354432304&use_mirror=iweb", @ScriptDir & "\" & $handbrakeDownloadName, 1, 1)
			Sleep(2000)
				$versionz = $versionz + 1
				;$iMsgBoxAnswer = MsgBox(0, "Filename", "http://downloads.sourceforge.net/project/handbrake/" & $versionx & "." & $versiony & "."  & $versionz & "/" & $handbrakeDownloadName & "?r=&ts=1354432304&use_mirror=iweb", 30)
				Until InetGetInfo($hDownload, 4) = 0 ; Check if the file exists
			Else
				Do
					If $versionz > 9 Then
						$versionz = 0
						$versiony = $versiony + 1
					EndIf
					If $versiony >9 Then
						$versionz = 0
						$versiony = 0
						$versionx = $versionx + 1
					EndIf
				Local $handbrakeDownloadName = "HandBrake-" & $versionx & "." & $versiony & "."  & $versionz & "-i686-Win_GUI.exe"
				Local $hDownload = InetGet("http://downloads.sourceforge.net/project/handbrake/" & $versionx & "." & $versiony & "."  & $versionz & "/" & $handbrakeDownloadName & "?r=&ts=1354432304&use_mirror=iweb", @ScriptDir & "\" & $handbrakeDownloadName, 1, 1)
			Sleep(2000)
				$versionz = $versionz + 1
				;$iMsgBoxAnswer = MsgBox(0, "Filename", $hDownload, 30)
			Until InetGetInfo($hDownload, 4) = 0 ; Check if the file exists
				;Local $hDownload = InetGet("http://downloads.sourceforge.net/project/handbrake/0.9.6/HandBrake-0.9.6-i686-Win_GUI.exe?r=http%3A%2F%2Fhandbrake.fr%2Fdownloads.php&ts=1332919033&use_mirror=superb-dca2", @ScriptDir & "\HandBrake-0.9.6-i686-Win_GUI.exe", 1, 1)
			EndIf
			SplashTextOn("Downloading", "", 350, 50, -1, -1, 4, "", 18)
			Do
				Local $hDownloadSize = Round((InetGetInfo($hDownload, 1) / 1024), 2)
				Local $hDownloadProgress = Round((InetGetInfo($hDownload, 0) / 1024), 2)
				Local $message = $hDownloadProgress & "K of " & $hDownloadSize & "K"
				ControlSetText("Downloading", "", "Static1", $message)
				; wait for a bit before checking to see if the download is complete
				Sleep(250)
			Until InetGetInfo($hDownload, 2) ; Check if the download is complete.
			SplashOff()
			Local $nBytes = InetGetInfo($hDownload, 0)
			InetClose($hDownload) ; Close the handle to release resourcs.
			SplashOff()
			;Without this slight pause the program gets caught in a loop and tries to download it again
			Sleep(250)
			;Run the Handbrake installer
			If FileExists (@ScriptDir & "\" & $handbrakeDownloadName) Then
				$runDVDInstaller = RunWait(Chr(34) & @ScriptDir & "\" & $handbrakeDownloadName & Chr(34) & " /S /D")
			ElseIf (@ScriptDir & "\HandBrake-0.9.6-i686-Win_GUI.exe") Then
				$runDVDInstaller = RunWait(Chr(34) & @ScriptDir & "\" & $handbrakeDownloadName & Chr(34) & " /S /D")
			EndIf
			; if the install is successfull, run the ini settings function.
			If $runDVDInstaller = 1 Then
				SettingsCheck()
			EndIf
		Case $iMsgBoxAnswer = 2 ;Cancel
			GUISetState(@SW_HIDE)
	EndSelect
	Return
EndFunc   ;==>DownloadHandBrake
;debugit

; This function is used to check th ini file and make sure the required programs are available to rip a disk
; Then the settings are stored in the ini file for later use
Func SettingsCheck()
	;Check to make sure MakeMKV Exists.
	; right now the logic is pretty poor here.  Since I developed this on 64bit windows
	; and MakeMKV is not current 64bit there are some assumptions here.
	; If the user is on XP they will need to update this path when they validate the settings
	If FileExists(@ProgramFilesDir & " (x86)\MakeMKV\makemkvcon64.exe") Then
		$MakeMKVPath = @ProgramFilesDir & " (x86)\MakeMKV\makemkvcon64.exe"
	ElseIf FileExists(@ProgramFilesDir & "\MakeMKV\makemkvcon.exe") Then
		$MakeMKVPath = @ProgramFilesDir & "\MakeMKV\makemkvcon.exe"
	Else
		; run the download function to download MakeMKV
		DownloadMakeMKV()
		;this assumes you are on 64bit windows, the user will need to verify this in the ini config dialog
		If FileExists ("C:\Program Files (x86)") Then
			$MakeMKVPath = @ProgramFilesDir & " (x86)\MakeMKV\makemkvcon64.exe"
		Else
			$MakeMKVPath = @ProgramFilesDir & "\MakeMKV\makemkvcon.exe"
		EndIf
	EndIf
	; Lets do the same logic for HandBrake
	If FileExists("C:\Program Files\Handbrake\HandBrakeCLI.exe") Then
		$handbrakePath = "C:\Program Files\Handbrake\HandBrakeCLI.exe"
	ElseIf FileExists("C:\Program Files (x86)\Handbrake\HandBrakeCLI.exe") Then
		$handbrakePath = "C:\Program Files (x86)\Handbrake\HandBrakeCLI.exe"
	Else
		; run the download function to download MakeMKV
		DownloadHandBrake()
		;this assumes you are on 64bit windows, the user will need to verify this in the ini config dialog
		If FileExists ("C:\Program Files (x86)") Then
			$handbrakePath = @ProgramFilesDir & " (x86)\Handbrake\HandBrakeCLI.exe"
		Else
			$handbrakePath = @ProgramFilesDir & "\Handbrake\HandBrakeCLI.exe"
		EndIf
	EndIf
	;Additional redundancy check.  Likely unnecessary, but....
	;Check to see if the ini file exists.  If not, invoke the settings function.
	$var = IniReadSectionNames($autoripini)
	; If the reading of the ini file failed, we creat a default ini by calling the create function
	If @error Then
		; Call the function to create the default Ini file
		CreateDefaultIni()
	EndIf
EndFunc   ;==>SettingsCheck

;debugit
Func _sendAutoRipEmail ($emailType, $emailBody)

Local $debugLogList = _FileListToArray(@ScriptDir, "AutoRip2MKV_Ver_*.log", 1)
;_FileListToArray($sPath [, $sFilter = "*" [, $iFlag = 0]])

	; email type 0=user, 1=debug

	If $emailType = 0 Then
		$emailTo = "autorip2mkv@gmail.com"
		$emailSubject = "Failed Rip - " & $driveLabel
		If $emailBody = "" Then
			$emailBody = FileRead($MovieLocation & "\MKVrip.txt", -1)
		EndIf
		$emailAttachment = @ScriptDir & "\" & $debugLogList[$debugLogList[0]]
	EndIf

	If $emailType = 1 Then
		$emailTo = "autorip2mkv@gmail.com"
		$emailCC = $userEmail
		$emailSubject = "DEBUG AutoRip2MKV - " & $userEmail
		If $emailBody = "" Then
			$emailBody = FileRead($MovieLocation & "\MKVrip.txt", -1)
		EndIf
		$emailAttachment = @ScriptDir & "\" & $debugLogList[$debugLogList[0]]
	EndIf

	_sendEmail($emailTo, $emailCC, $emailSubject, $emailBody, $emailAttachment)

EndFunc
;debugit

Func checkMKVVersion($DVDSource)
	local $tempMakeMKVOutput = $finalMovieLocation & "\tempMakeMKVfile.txt"
	local $CountLines = _FileCountLines($tempMakeMKVOutput)
	For $i = 1 To $CountLines Step 1
		local $tempLogLine = FileReadLine ( $tempMakeMKVOutput , $i )
		If StringInStr ($tempLogLine, "old") Then
			MsgBox(0, "Rip Failed", "Check that MakeMKV is the latest version. Click OK to download the latest." , 60)
			$emailBody = "Check that MakeMKV is the latest version."
			DownloadMakeMKV()
			_ExitAutoRip ($emailBody)
		ElseIf StringInStr ($tempLogLine, "enter a registration key") Then
			MsgBox(0, "Rip Failed", "Check that MakeMKV has a valid registration key. Click OK to open MakeMKV to add your registration key." , 60)
			local $runMakeMKV = Run("C:\Program Files (x86)\MakeMKV\makemkv.exe", "", @SW_MAXIMIZE)
			local $runMakeMKV = Run("C:\Program Files\MakeMKV\makemkv.exe", "", @SW_MAXIMIZE)
			$emailBody = "Check that MakeMKV has a valid registration key."
			_ExitAutoRip ($emailBody)
		EndIf
	Next
EndFunc

Func OKClick()
	;Preferences have been set, hide the dialog and proceed.
	GUISetState(@SW_HIDE)
	$MakeMKVPath = GUICtrlRead($MakeMKVInput)
	$tempPath = GUICtrlRead($TempInput)
	$finalPath = GUICtrlRead($FinalInput)
	$sleepDelay = GUICtrlRead($MonitorDelay)
	$convertAppleTV = GUICtrlRead($GUI_CHECKED)
	; If the user has selected a value less than 5 seconds, force the value to 5 seconds.
	If $sleepDelay < 2000 Then
		$sleepDelay = 2000
	EndIf
	Local $installQuestion = MsgBox(4, 'Apple Conversion', 'Do you want to convert to Apple File Formats?')
	If $installQuestion = 6 Then
		$convertAppleTV = "1"
		Local $installQuestion2 = MsgBox(4, 'Keep MKV After Apple Conversion', 'Do you want to keep the MKV file after conversion to Apple formats?')
		If $installQuestion2 = 6 Then
			$keepMKV = "1"
		Else
			$keepMKV = "0"
		EndIf
	Else
		$convertAppleTV = "0"
		$keepMKV = "1"
	EndIf
	; Fill the array to be written to the ini file
	If $episodeSupport = "" Then
		$episodeSupport = "0"
	EndIf
	Dim $settingsData[12][2] = [["MakeMKVPath", $MakeMKVPath],["TempPath", $tempPath],["FinalPath", $finalPath],["Delay", $sleepDelay],["ConvertForAppleTV", $convertAppleTV],["HandBrakePath", $handbrakePath],["MinimumTitleLength", "1200"],["KeepMKV", $keepMKV],["HandBrakeCMDLine", $handbrakeCommandLine],["EpisodeSupport", $episodeSupport],["EmailAddress",$userEmail],["DebugEnable",0]]
	; Write the ini file
	IniWriteSection($autoripini, "AutoRipSettings", $settingsData, 0)
	; return to the main function to await a disk insertion!
	$emailBody = "NOEMAIL"
	_ExitAutoRip ($emailBody)
EndFunc   ;==>

Func strClean($a)
	Local $b = "1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_-"
	Return StringRegExpReplace($a, "[^" & $b & "]", "")
EndFunc   ;==>strClean

; the following functions are used to allow the user to browse and populate the ini settings dialog
Func MakeMKVLocationClick()
	$file = FileOpenDialog("Choose file...", @ProgramsCommonDir, "All (*.exe)")
	If @error = 0 Then
		GUICtrlSetData($MakeMKVInput, $file)
	EndIf
EndFunc   ;==>MakeMKVLocationClick

Func RipLocationClick()
	$iniDrive = FileSelectFolder("Choose a folder.", "")
	If @error = 0 Then
		GUICtrlSetData($TempInput, $iniDrive)
	EndIf
EndFunc   ;==>RipLocationClick

Func FinalLocationClick()
	$iniDrive = FileSelectFolder("Choose a folder.", "")
	If @error = 0 Then
		GUICtrlSetData($FinalInput, $iniDrive)
	EndIf
EndFunc   ;==>FinalLocationClick


Func ConfirmSettingsClick()
EndFunc   ;==>ConfirmSettingsClick

;debugit
; This function is called if the user does not have MakeMKV in the predefined location (yes, its hardcoded).
Func DownloadMakeMKV()
	$versionx=1
	$versiony=7
	$versionz=8
	Dim $iMsgBoxAnswer
	; Promp the user with an option to download MakeMKV
	; If the user DOES have it installed in a custom location, they can click cancel and be prompted with the
	; ini settings dialog box.
	$iMsgBoxAnswer = MsgBox(33, "MakeMKV Is Missing or Outdated - Download?", "MakeMKV as defined in the " & $autoripini & " file cannot be found or is out of date." & @CRLF & "" & @CRLF & "If you have MakeMKV, Click Cancel to edit your preferences" & @CRLF & "" & @CRLF & "If you would like to download the latest MakeMKV, Click OK")
	; Download the file
	; show a "progress indicator" based on file length.
	Select
		Case $iMsgBoxAnswer = 1 ;OK
			Do
				If $versionz > 50 Then
					$versionz = 0
					$versiony = $versiony + 1
				EndIf
				If $versiony >50 Then
					$versionz = 0
					$versiony = 0
					$versionx = $versionx + 1
				EndIf
			Local $makeMKVDownloadName = "Setup_MakeMKV_v" & $versionx & "." & $versiony & "."  & $versionz & ".exe"
			Local $hDownload = InetGet("http://www.makemkv.com/download/" & $makeMKVDownloadName, @ScriptDir & "\" & $makeMKVDownloadName, 1, 1)
			Sleep(2000)
			$versionz = $versionz + 1
			;$iMsgBoxAnswer = MsgBox(0, "Filename", "http://www.makemkv.com/download/" & $makeMKVDownloadName, @ScriptDir & "\" & $makeMKVDownloadName, 30)
			Until InetGetInfo($hDownload, 4) = 0   ; Check if the file exists
			SplashTextOn("Downloading", "", 350, 50, -1, -1, 4, "", 18)
			Do
				Local $hDownloadSize = Round((InetGetInfo($hDownload, 1) / 1024), 2)
				Local $hDownloadProgress = Round((InetGetInfo($hDownload, 0) / 1024), 2)
				Local $message = $hDownloadProgress & "K of " & $hDownloadSize & "K"
				ControlSetText("Downloading", "", "Static1", $message)
				; wait for a bit before checking to see if the download is complete
				Sleep(250)
			Until InetGetInfo($hDownload, 2) ; Check if the download is complete.
			SplashOff()
			Local $nBytes = InetGetInfo($hDownload, 0)
			InetClose($hDownload) ; Close the handle to release resourcs.
			SplashOff()
			;Without this slight pause the program gets caught in a loop and tries to download it again
			Sleep(250)
			;Run the MakeMKV installer
			$runDVDInstaller = RunWait(Chr(34) & @ScriptDir & "\" & $makeMKVDownloadName & Chr(34) & " /S /D")
			; if the install is successfull, run the ini settings function.
			If $runDVDInstaller = 1 Then
				SettingsCheck()
			EndIf
		Case $iMsgBoxAnswer = 2 ;Cancel
			GUISetState(@SW_HIDE)
	EndSelect
	Return
EndFunc   ;==>DownloadMakeMKV
;debugit

Func AutoRipSettingsClose()
	GUISetState(@SW_HIDE)
EndFunc   ;==>AutoRipSettingsClose

Func CreateDefaultIni()
	; The creates the GUI presented to the user for the settings
	; Right now the sleepDelay is not shown and must be manually changed in the ini file
	Opt("GUIOnEventMode", 1)
	#region ### START Koda GUI section ### Form=C:\Documents and Settings\Greg\Desktop\AutoRip\Form1.kxf
	$AutoRipSettings = GUICreate("AutoRip Settings", 440, 395, 358, 182)
	GUISetOnEvent($GUI_EVENT_CLOSE, "AutoRipSettingsClose")
	GUICtrlCreateLabel("MakeMKV Location", 56, 72, 184, 17)
	GUICtrlCreateLabel("Final Location", 56, 168, 150, 17)
	GUICtrlCreateLabel("Temporary Rip Location", 56, 120, 165, 17)
	If FileExists ("C:\Program Files (x86)") Then
		$MakeMKVInput = GUICtrlCreateInput("C:\Program Files (x86)\MakeMKV\makemkvcon64.exe", 56, 88, 321, 24)
	Else
		$MakeMKVInput = GUICtrlCreateInput("C:\Program Files\MakeMKV\makemkvcon.exe", 56, 88, 321, 24)
	EndIf
	GUICtrlSetLimit(-1, 40)
	$MakeMKVLocation = GUICtrlCreateButton("...", 384, 88, 27, 17, $BS_NOTIFY)
	$TempInput = GUICtrlCreateInput("C:\temp\Movies", 56, 136, 321, 24)
	$RipLocation = GUICtrlCreateButton("...", 384, 136, 27, 17, $BS_NOTIFY)
	$FinalInput = GUICtrlCreateInput("D:\Movies", 56, 184, 321, 24)
	$FinalLocation = GUICtrlCreateButton("...", 384, 184, 27, 17, $BS_NOTIFY)
	GUICtrlSetOnEvent(-1, "FinalLocationClick")
	$OK = GUICtrlCreateButton("OK", 169, 344, 75, 25, $BS_NOTIFY)
	GUICtrlSetOnEvent(-1, "OKClick")
	$Cancel = GUICtrlCreateButton("Cancel", 255, 344, 75, 25, $BS_NOTIFY)
	GUICtrlSetOnEvent(-1, "AutoRipSettingsClose")
	GUICtrlCreateLabel("Define the default settings below:", 48, 24, 271, 17)
	$SettingsGroup = GUICtrlCreateGroup("Settings Group", 48, 48, 377, 273)
	;$MonitorDelay = GUICtrlCreateInput("10000", 56, 280, 321, 24)
	;$Label2 = GUICtrlCreateLabel("Monitor Delay (10000 ms is minimum)", 56, 264, 216, 20)
	GUICtrlCreateGroup("", -99, -99, 1, 1)
	;$ConfirmSettings = GUICtrlCreateCheckbox("Confirm settings valid on startup", 88, 304, 177, 17)
	GUICtrlSetState(-1, $GUI_CHECKED)
	GUICtrlSetOnEvent(-1, "ConfirmSettingsClick")
	GUISetState(@SW_SHOW)
	#endregion ### END Koda GUI section ###
	While  1
		Sleep(100)
	WEnd

EndFunc   ;==>CreateDefaultIni

Func ripDisc($driveID, $titleID, $driveLabel)

	Local $MakeMKVOptions = '--robot --messages ' & '"' & $MovieLocation & '\MKVrip.txt"' & ' --decrypt --minlength=' & $minTitleLength & ' mkv disc:' & $driveID & ' ' & $titleID & ' ' & '"' & $MovieLocation & '"'
	Local $ripMKV = RunWait($MakeMKV & " " & $MakeMKVOptions, "", @SW_MINIMIZE)
	If $ripMKV >0 Then
		$emailBody = ""
		_ExitAutoRip($emailBody)
	EndIf
	$doFilesExist = _checkIfFilesExist("*.mkv")
	If Not $doFilesExist Then
		checkMKVVersion ($DVDSource)
	Else
		FileRecycle($MovieLocation & "\MKVRip.txt")
	EndIf
EndFunc   ;==>ripDisc

Func _renameMKV()
	;Rename the file in the folder to match the movie
	Local $fileSearch = $MovieLocation & "\"
	$file = _FileListToArray($fileSearch, "*.mkv")
	;_ArrayDisplay($file, 'Default Search')
	If $file[0] > 0 Then
		For $i = $file[0] To 1 Step -1
			$finalMKVNewName = $driveLabel & "_" & $i & ".mkv"
			FileMove($fileSearch & $file[$i], $fileSearch & $finalMKVNewName, 1)
		Next
	EndIf
EndFunc   ;==>_renameMKV

Func _checkIfFilesExist($searchExtension)
	Local $fileSearch = $MovieLocation
	$file = _FileListToArray($fileSearch, $searchExtension)
	;_ArrayDisplay($file, 'Default Search')

	If Not @error Then
		Return 1
	Else
		Return 0
	EndIf
EndFunc   ;==>_checkIfFilesExist


Func BlueRayTitle()
	Local $brTitle[3]
	Local $fileToTest = $DVDSource & 'BDMV\META\DL\bdmt_eng.xml'
	If $tempLocation <> "" Then
		$MovieLocation = $tempLocation
	Else
		$MovieLocation = $finalMovieLocation
	EndIf
	If StringRight($MovieLocation, 1) = "\" Then
		$MovieLocation = StringTrimRight($MovieLocation, 1)
	EndIf
	If FileExists($fileToTest) = 1 Then
		Local $fileString = FileRead($fileToTest)
		Local $aArray1 = _StringBetween($fileString, '<di:name>', '</di:name>')
		$brTitle[2] = $aArray1[0]
		If $brTitle[2] = "" Then
			$brTitle[2] = DriveGetLabel($DVDSource)
			$brTitle[2] = strClean($driveLabel)
			$driveLabel = strClean($brTitle[2])
		EndIf
		$MovieLocation = $MovieLocation & '\' & strClean($brTitle[2])
		DirCreate($MovieLocation)
		FileCopy($DVDSource & 'BDMV\META\DL\*.jpg', $MovieLocation, 9)
		;For $i = 0 To 50 Step 1
		;	If StringInStr($fileString, '="' & $i & '">' & $brTitle[2]) > 0 Then
				;$iMsgBoxAnswer = MsgBox(33, "StringInStr!", '="' & $i & '">' & $brTitle[2])
				$brTitle[1] = 0
		;		ExitLoop
		;	EndIf
		;Next
	Else
		$driveLabel = DriveGetLabel($DVDSource)
		If $driveLabel <> strClean($driveLabel) Then
			$driveLabel = strClean($driveLabel)
		EndIf
		$brTitle[2] = $driveLabel
		$MovieLocation = $MovieLocation & '\' & $driveLabel
		DirCreate($MovieLocation)
		FileCopy($DVDSource & 'BDMV\META\DL\*.jpg', $MovieLocation, 9)
		$brTitle[1] = 0
	EndIf
	Return $brTitle
EndFunc   ;==>BlueRayTitle

Func _CreateFileConversionList($MovieLocation, $driveLabel)
	Local $ripListFile = (@ScriptDir & "/convertlist.log")
	If FileExists($ripListFile) = 0 Then
		_FileCreate($ripListFile)
	EndIf
	Local $CountLines = _FileCountLines($ripListFile)
	;MsgBox(64, "RipList", "There are " & $CountLines & " in the convertlist.log.")
	Local $emptyLineToWriteTo = $CountLines + 1
	_FileWriteToLine($ripListFile, $emptyLineToWriteTo, $MovieLocation & "," & $driveLabel, 0)
EndFunc

Func _Quit()
	MsgBox(33, "AutoRip Canceled", "Preferences Are Not Set or Set Incorrectly.  Dialog Closing in 60 Seconds")
	$emailBody = "AutoRip2MKV Preferences Are Not Set or Set Incorrectly."
	_ExitAutoRip($emailBody)
EndFunc   ;==>_Quit

;debugit
Func _ExitAutoRip ($emailBody)

	If $emailBody <> "NOEMAIL" Then
		_sendAutoRipEmail ($debugEnable, $emailBody)
	EndIf

	$Mode = _WinAPI_SetErrorMode($SEM_FAILCRITICALERRORS)
	While 1
		$x=$x+1
		If Not FileExists($MovieLocation & "\MKVRip.txt") Then
			Switch _WinAPI_GetLastError()
				Case 21 ; ERROR_NOT_READY
					; Nothing
				Case Else
					If $CmdLine[0] > 0 Then
						_WinAPI_EjectMedia(StringTrimRight($CmdLine[1], 1))
					EndIf
					;Sleep(1000)
					Exit
			EndSwitch
		EndIf
		If $x>30 Then
			_WinAPI_EjectMedia(StringTrimRight($CmdLine[1], 1))
			MsgBox(0, "Rip Failed", "Rip Failed for an unknown reason. Please check to see if the disk needs cleaning or repairs." , 60)

			Exit
		EndIf
		Sleep(100)
	WEnd
	_WinAPI_SetErrorMode($Mode)
Exit
EndFunc
;debugit
Func _Main($driveID)
	;Call the function to check that MakeMKV is installed
	SettingsCheck()
	$iniFile = IniReadSection($autoripini, "AutoRipSettings")

	If @error Then
		SettingsCheck()
	EndIf
	$MakeMKV = $iniFile[1][1]
	$tempLocation = $iniFile[2][1]
	$finalMovieLocation = $iniFile[3][1]
	$sleepDelay = $iniFile[4][1]
	$convertAppleTV = $iniFile[5][1]
	$handbrakePath = $iniFile[6][1]
	$minTitleLength = $iniFile[7][1]
	$keepMKV = $iniFile[8][1]
	$handbrakeCommandLine = $iniFile[9][1]
	$episodeSupport = $iniFile[10][1]
	$userEmail = $iniFile[11][1]
	$debugEnable = $iniFile[12][1]

	If $episodeSupport = "1" Then
		$episodeSupport = "all"
	ElseIf $episodeSupport = "0" Then
		;do nothing
	ElseIf $episodeSupport = "" Then
		$episodeSupport = "all"
	EndIf

	dim $timerdelay = 5000
	; Check to make sure the sleep delay is at least 5 second
	If $sleepDelay < 2000 Then
		$sleepDelay = 2000
	EndIf
	;While $driveLabel = ""
		;$timerdelay = $timerdelay + $timerdelay
		$driveLabel = DriveGetLabel($DVDSource)
		$driveLabel = strClean($driveLabel)
	;	Sleep($sleepDelay)
	;WEnd
	If FileExists($DVDSource & "VIDEO_TS\VIDEO_TS.BUP") Then
		If $tempLocation <> "" Then
			$MovieLocation = $tempLocation & "\" & $driveLabel & "\"
		Else
			$MovieLocation = $finalMovieLocation & "\" & $driveLabel & "\"
		EndIf
		If StringRight($MovieLocation, 1) = "\" Then
			$MovieLocation = StringTrimRight($MovieLocation, 1)
		EndIf
		If $driveLabel <> "" Then
				If FileExists ($MovieLocation) Then
					$MovieLocation = $MovieLocation & "_1"
				EndIf

			DirCreate ($MovieLocation)
			ripDisc($driveID, $episodeSupport, $driveLabel)
		EndIf
	ElseIf FileExists($DVDSource & "BDMV\META\DL\") Then
		$blueRayTitle = BlueRayTitle()
		;_ArrayDisplay($blueRayTitle, 'Default Search')
		;$iMsgBoxAnswer = MsgBox(33, "$blueRayTitle!", "$blueRayTitle = " & $blueRayTitle)
		If $tempLocation <> "" Then
			$MovieLocation = $tempLocation & "\" & strClean($blueRayTitle[2]) & "\"
		Else
			$MovieLocation = $finalMovieLocation & "\" & strClean($blueRayTitle[2]) & "\"
		EndIf
		If StringRight($MovieLocation, 1) = "\" Then
			$MovieLocation = StringTrimRight($MovieLocation, 1)
		EndIf
		$driveLabel = strClean($blueRayTitle[2])
		If $driveLabel <> "" Then
			If FileExists ($MovieLocation) Then
				$MovieLocation = $MovieLocation & "_1"
			EndIf
			ripDisc($driveID, $blueRayTitle[1], $driveLabel)
		EndIf
	EndIf
	$doFilesExist = _checkIfFilesExist("*.mkv")
	;iMsgBoxAnswer = MsgBox(33, "DEBUG!", "$doFilesExist = " & $doFilesExist)
	If $doFilesExist Then
		;iMsgBoxAnswer = MsgBox(33, "renameMKV!", "$doFilesExist = " & $doFilesExist)
		_renameMKV()
		Sleep(5000)
	EndIf
	$doFilesExist = _checkIfFilesExist("*.mkv")
	;iMsgBoxAnswer = MsgBox(33, "AfterrenameMKV!", "$doFilesExist = " & $doFilesExist)
	If $doFilesExist Then
		; If the user wants to convert it for use in appletv, lets do this now.
		If $convertAppleTV = "1" Then
			;iMsgBoxAnswer = MsgBox(33, "convert!", "$driveLabel = " & $driveLabel)
			_CreateFileConversionList($MovieLocation, $driveLabel)
			$convertUsingHandbrake = ShellExecute("ConvertMKV.exe", "", @ScriptDir, "", @SW_MAXIMIZE)
			;$convertUsingHandbrake = Run(@ScriptDir & "\ConvertMKV.exe", "", @SW_MAXIMIZE)
		ElseIf $tempLocation <> "" Then
			$doFilesExist = _checkIfFilesExist("*.*")
			;MsgBox(33, "copy!", "$driveLabel = " & $driveLabel & " $MovieLocation = " & $MovieLocation)
			If $doFilesExist Then
				$moveFiles = ShellExecuteWait(@ScriptDir & "\CopyFiles.exe", $MovieLocation & " " & $driveLabel)
			EndIf
		EndIf
	EndIf
	$emailBody = "NOEMAIL"
	_ExitAutoRip($emailBody)
EndFunc   ;==>_Main

Func checkDriveSpace ($drivetocheck)
	Local $iFreeSpace = DriveSpaceFree($drivetocheck & "\") ; Find the free disk space of the home drive, generally this is the C:\ drive.
	Local $z = (Round($iFreeSpace/1000, 2)) ;returns 120
	If $z < 8 Then
		MsgBox(0, "Free Space:", "You have " & $z & " GB free. It is recommended to have at least 8 GB free.", 60)
		$emailBody = "You have " & $z & " GB free. It is recommended to have at least 8 GB free."
		_ExitAutoRip($emailBody)
	EndIf
EndFunc

If @error Then
	SettingsCheck()
	; if the ini file checks out, define the $driveletter variable from the ini file.
	; grab the value defined for sleep delay in ms
Else
	$MakeMKV = $iniFile[1][1]
	$tempLocation = $iniFile[2][1]
	$finalMovieLocation = $iniFile[3][1]
	$sleepDelay = $iniFile[4][1]
	$convertAppleTV = $iniFile[5][1]
	$handbrakePath = $iniFile[6][1]
	$minTitleLength = $iniFile[7][1]
	$keepMKV = $iniFile[8][1]
	$handbrakeCommandLine = $iniFile[9][1]
	$episodeSupport = $iniFile[10][1]
	$userEmail = $iniFile[11][1]
	$debugEnable=$iniFile[12][1]

	If $episodeSupport = "1" Then
		$episodeSupport = "all"
	ElseIf $episodeSupport = "0" Then
		;do nothing
	ElseIf $episodeSupport = "" Then
		$episodeSupport = "all"
	EndIf
EndIf


; Get the drive passed from the OS that will be used to rip the file.  Assign the DVDSource and drive ID from this.
If $CmdLine[0] > 0 Then

	local $tempMakeMKVOutput =  $finalMovieLocation & "\tempMakeMKVfile.txt"
	local $executeMakeMKVOutput = RunWait('"' & $MakeMKV & '" -r --cache=1 info disc:9999 --messages=' & $tempMakeMKVOutput)
	If FileExists ($tempMakeMKVOutput) Then
		checkDriveSpace($finalMovieLocation)
		checkDriveSpace($tempLocation)
		checkMKVVersion($DVDSource)
		$DVDSource = StringTrimRight($CmdLine[1], 1)
		local $sLabel = '"' & DriveGetLabel($DVDSource & "\") & '"'
		local $CountLines = _FileCountLines($tempMakeMKVOutput)
		For $i = 1 To $CountLines Step 1
		local $tempLogLine = FileReadLine ( $tempMakeMKVOutput , $i )
		local $splitString = StringSplit ($tempLogLine, ",")
		If $splitString[0] > 6 Then
			local $tempDriveLabel = $splitString[6]
				If $sLabel = $tempDriveLabel Then
					$driveID = StringTrimLeft($splitString[1], 4)
					$DVDSource = $DVDSource & '\'
					ExitLoop
				EndIf
			EndIf
		Next
	Else
		MsgBox(0, "Rip Failed", "Final destination does not exist. Check your ini file. Dialog closing in 60 seconds." , 60)
		CreateDefaultIni()
		$emailBody = "AutoRip2MKV Final destination does not exist. Check your ini file."
		_ExitAutoRip($emailBody)
		EndIf
EndIf


_Main($driveID)
$emailBody = "NOEMAIL"
_ExitAutoRip($emailBody)


